<?php

/**
 * IndexController is the default controller for this application
 */
class LoginController extends BrowseControllerBase {
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		
		// Set page name
		$this->setPageName ( 'login' );
		$this->smarty->assign ( 'listMonth', CommonDataService::getMonth () );
		$this->smarty->assign ( 'listDay', CommonDataService::getDay () );
		$this->smarty->assign ( 'listYear', CommonDataService::getYear () );
		$this->smarty->assign ( 'listCountry', CommonDataService::getCountrylist () );
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 */
	public function indexAction() {
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Login/index.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
	}
	
	/**
	 * Action when user login to the system
	 *
	 * @return next action
	 */
	public function loginAction() {
		$this->smarty->assign ( 'LOGIN_PAGE', true );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Login/index.tpl' );
		$username = $this->getPost ( 'username', '' );
		$password = $this->getPost ( 'password', '' );
		
		$isError = false;
		$urlCallBack = $this->getPost ( 'urlCallBack', '' );
		if (! empty ( $urlCallBack )) {
			$_SESSION ['urlCallBack'] = $urlCallBack;
		}
		if (empty ( $username ) || empty ( $password )) {
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
			return null;
		}
		
		$usersDataService = new UsersDataService ();
		//$result = $usersDataService->login($username, $password);
		$result = $usersDataService->loginCustomer ( $username, $password, 0 );
		if ($result == SUCC) {
			$this->loginsuccessAction ();
		} else {
			$isError = true;
			$this->smarty->assign ( 'isError', $isError );
			$this->smarty->assign ( 'errorLoginMessage', 'Sorry, but we could not find login details using the information you supplied. Please try again!' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
		}
	}
	
	/**
	 * Login Ajax Controller
	 */
	public function aloginAction() {
		$result = ERROR;
		$message = 'Login Fails. Please try again!';
		$username = $this->getPost ( 'username', '' );
		$password = $this->getPost ( 'password', '' );
		
		$usersDataService = new UsersDataService ();
		//$result = $usersDataService->login($username, $password);
		$result = $usersDataService->loginCustomer ( $username, $password, 0 );
		if ($result == SUCC) {
			$authentication = new Authentication ();
			if ($authentication->isMember () == true) {
				
				$result = SUCC;
				$message = "Login successfully. Please try again!";
				
				if (isset ( $_SESSION [SESSION_DEMO_MODE] ) && $res->username != DEMO_USERNAME) {
					// Unregister SESSION_DEMO_MODE
					session_unregister ( SESSION_DEMO_MODE );
				}
			} else {
				$result = ERROR;
				$message = 'Login Fails. Please try again!';
			}
		}
		
		$rturn = array ("error" => $result, "message" => $username . $password );
		
		echo Zend_Json::encode ( $rturn );
		exit ();
	
	}
	
	/**
	 * Action when user login successfully
	 *
	 * @return next action
	 */
	private function loginsuccessAction() {
		$authentication = new Authentication ();
		if ($authentication->isMember () == true) {
			if (isset ( $_SESSION ['urlCallBack'] ) && ! is_null ( $_SESSION ['urlCallBack'] )) {
				$url = $_SESSION ['urlCallBack'];
				unset ( $_SESSION ['urlCallBack'] );
				CommonUtils::redirect ( $url );
				return - 1;
			}
			
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/MyAccount';
			CommonUtils::redirect ( $url );
		} else {
			
			$this->smarty->assign ( 'errorLoginMessage', 'Sorry, Only Customer can access. Please try again!' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
		}
	
	}
	
	/**
	 * Create capcha for imagesecurity
	 *
	 */
	public function createsecurityAction() {
		$width = $this->getQuery ( 'width', 120 );
		$height = $this->getQuery ( 'height', 40 );
		$characters = $this->getQuery ( 'characters', 6 );
		$captcha = new CaptchaSecurityImages ( $width, $height, $characters );
	}
	
	/**
	 * Forgot Password Handling
	 */
	public function forgotpasswordAction() {
		
		require_once (APPLICATION_PATH . '/Utilities/PHPUtils/MyMailUtils.php');
		
		$usersDataService = new UsersDataService ();
		$email = $this->getPost ( 'email', '' );
		
		if (! empty ( $email )) {
			//$usersEntity = $usersDataService->getByEmail($email);
			$usersEntity = $usersDataService->getByEmailAndOwnerId ( $email, 0 );
			//Only change password for Normal User
			if (! is_null ( $usersEntity ) && ! is_null ( $usersEntity->id ) && $usersEntity->userType == ROLE_MEMBER) {
				$password = "8" . CommonUtils::randomNumber ( 5 );
				
				$authenticate = new Authentication ();
				
				// Update password
				$usersEntity->password = $authenticate->encryptPassword ( $password );
				$usersDataService->update ( $usersEntity );
				
				$settingsDataService = new SettingsDataService ();
				$adminEmail = $settingsDataService->getValue ( SETTINGS_ADMIN_EMAIL );
				$adminName = $settingsDataService->getValue ( SETTINGS_ADMIN_NAME );
				// Sending email to customer
				//$adminEmail = ADMIN_EMAIL;
				//$adminName = ADMIN_NAME;
				

				///send thank mail to sender
				$mailer = new MyMailUtils ();
				$mailer->addFrom ( $adminEmail, $adminName );
				$mailer->addTo ( $usersEntity->email, $usersEntity->firstName . " " . $usersEntity->lastName );
				
				$emailReplace = array ($usersEntity->firstName, $usersEntity->lastName, $usersEntity->email, $password, Zend_Registry::get ( 'config' )->APPLICATION_URL . '/' . 'Browse' );
				$contentEmail = SystemEmailDataService::getEmailContent ( SYSTEM_EMAIL_RESEND_PASSWORD, $emailReplace );
				$mailSubject = $contentEmail ['subject'];
				$mailContent = $contentEmail ['message'];
				$resultSendmail = $mailer->send ( $mailSubject, $mailContent );
				$mailer->resetAll ();
				
				$rturn = array ("error" => true, "message" => $email );
			
			} else {
				$rturn = array ("error" => false, "message" => $email );
			}
		
		} else {
			$rturn = array ("error" => false, "message" => $email );
		
		}
		echo Zend_Json::encode ( $rturn );
		exit ();
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'Browse/Login/forgotpassword.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl');
	}
	
	/**
	 * Activate User
	 *
	 */
	public function activateAction() {
		$code = $this->getQuery ( 'code', '' );
		$usersDataService = new UsersDataService ();
		if (! empty ( $code )) {
			$usersEntity = $usersDataService->getByActivationCode ( $code );
			if (! is_null ( $usersEntity ) && $usersEntity->status == UsersEntity::INACTIVE) {
				$usersEntity->hasVerified = 1;
				$usersEntity->status = UsersEntity::ACTIVE;
				$usersDataService->update ( $usersEntity );
				
				$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Login/activated.tpl' );
				$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
				
				// Send Welcome mails.
				$usersDataService->sendThankMail ( $usersEntity );
			} else {
				$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Browse/Login/invalid_code.tpl' );
				$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
			
			}
		}
	
	}
	
	/**
	 * This action will automatically login to our system as DEMO user	 *
	 */
	public function demoAction() {
		$username = DEMO_USERNAME;
		$password = DEMO_PASSWORD;
		$usersDataService = new UsersDataService ();
		$result = $usersDataService->login ( $username, $password );
		
		if ($result == SUCC) {
			$this->loginsuccessAction ();
			
			// Set DEMO mode
			$_SESSION [SESSION_DEMO_MODE] = true;
		}
	
	}
}
